package ui;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import net.ParaReader;
import net.ParaWriter;
import net.Answer;
import net.MSGType;
import net.Question;
import net.dethi;
import net.docghi;
import net.docghi2;
import net.dstraloi;
import net.loadlientuc;
import net.quanlydocviet;
import net.tonghopdocghi;
import net.traloi;


import net.Queues;

import net.msg;


import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Group;

import db.cauhoicoso;
import org.eclipse.wb.swt.SWTResourceManager;

public class Client {

	protected Shell shell;
	private ObjectOutputStream out = null;
    private ObjectInputStream in = null;
	public  Queues<msg>SendQueue=new Queues<msg>();
	public  Queues<msg>CMDqueue=new Queues<msg>();
	private Button btnKetNoi;
	private Label labelchay;
	private Button bntA;
	private Button bntB;
	private Button bntC;
	private Button bntD;
	private String Mach;
	private Question Data;
	private String str;
	private String dapan;
	private Socket socket;
	private Label labelA;
	private Label labelB;
	private Label labelC;
	private Label labelD;
	private Label labelnoidungcauhoi;
	private String IP;
	private Button bntexit;
	private Group group;
	private Label lblNewLabel;
	private Label lblNewLabel_1;
	private Text txttenthisinh;
	private Text txtdentulop;
	private Group group_1;
	private Button bntnext;
	private Label lblNewLabel_2;
	private Text txtsobaodanh;
	private Group group_2;
	private Group groupketqua;
	private dethi dethi=new dethi();
	MessageBox ms;
	private int tongsocautrongde;
	private int next=0;
	private dstraloi dstl=new dstraloi();
	private int back=0;
	static int interval;
	static Timer timer;
	private int tg;
	private Label labelh;
	private Label labelph;
	private Label labels;
	private int t=1;
	private int h;
	private int ph;
	private int s;
	private Label lblH;
	private Label lblNewLabel_5;
	private Label lblS;
	private int batdauthi=0;
	private Button btnNewButton;
	private Button bnthoangthanh;
	private Label labelnhande;
	private Button btnGui;
	private int dong=1;
	private Label txtsocaudung;
	private Label txtdiem;
	
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Client window = new Client();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			
			
			if (!display.readAndDispatch()) {
				//display.sleep();
			}
			
				if(dong==0)
				{
					bntnext.setEnabled(false);
					bnthoangthanh.setEnabled(false);
					if(dstl.Size()<dethi.getSize())
					{
						int chenhlech=dethi.getSize()-dstl.Size();
						 int tang=0;
						while(chenhlech>=1)
						{
							traloi tl=new traloi(dethi.get(dstl.Size()+tang).getId(), dethi.get(dstl.Size()+tang).getMACAUHOI(), dethi.get(dstl.Size()+tang).getNOIDUNG(), dethi.get(dstl.Size()+tang).getMALINHVUC(), dethi.get(dstl.Size()+tang).getMUCDO(), dethi.get(dstl.Size()+tang).getA(),dethi.get(dstl.Size()+tang).getB(),dethi.get(dstl.Size()+tang).getC(), dethi.get(dstl.Size()+tang).getD(), dethi.get(dstl.Size()+tang).getDUNG(), "D");
							dstl.add(tl);
							try {
								IP = socket.getInetAddress().getLocalHost().getHostAddress();
								msg traloin=new msg(new MSGType().getSENT_DATA(),IP, dstl, "client");
								SendQueue.enqueue(traloin);
							} catch (UnknownHostException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
							tang++;
						}
						
					}
					else
					{
						String IP;
						try {
							IP = socket.getInetAddress().getLocalHost().getHostAddress();
							msg traloin=new msg(new MSGType().getSENT_DATA(),IP, dstl, "client");
							SendQueue.enqueue(traloin);
						} catch (UnknownHostException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}
					dong=1;
				}
			if(batdauthi==1)
			{
				if(t==0)
				{
					clock(tg);
					t=1;
				}
				
				labelh.setText(Integer.toString(interval/3600));
	            labelph.setText(Integer.toString((interval%3600)/60));
	            labels.setText(Integer.toString(((interval%3600)%60)));
            
            if(!CMDqueue.isEmpty())
			{	
					
            
					msg dulieu=CMDqueue.dequeue();
					
					if(dulieu.getType().equals(new MSGType().getSENT_DATA()))
					{
						dethi=(dethi)dulieu.getData();
						tongsocautrongde= dethi.getSize();
						tg=Integer.parseInt(dulieu.getStr());
						t=0;
						dstl.setMakythi(dethi.getMasokythi());
						labelnoidungcauhoi.setText(dethi.get(0).getNOIDUNG());
						labelA.setText(dethi.get(0).getA());
						labelB.setText(dethi.get(0).getB());
						labelC.setText(dethi.get(0).getC());
						labelD.setText(dethi.get(0).getD());
						
						//if(dulieu.getType().equals(new MSGType().getCOMPLETED()))
					//	{
						//	txtsocaudung.setText(dulieu);
						///}
						
						
			            
						//str=dulieu.getStr();//ma so ki thi
						
					}
					if(dulieu.getType().equals(new MSGType().getCOMPLETED()))
					{
						
						Answer an=(Answer)dulieu.getData();
						
						txtsocaudung.setText(an.getMASOKYTHI());
						txtdiem.setText(an.getMASOKYTHI()+"/"+an.getMaCH());
					}
					
					if(dulieu.getType()==new MSGType().getDISCONNECTED())
					{
						msg closeCMD = new msg(new MSGType().getCLIENT_UI_CLOSE(), "", "","");
						SendQueue.enqueue(closeCMD);  //Close sending thread
						break;
						
					}
				
				
				
			}else
			{
				try {
					Thread.sleep(5);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}
			}
			if(!CMDqueue.isEmpty())
			{	
					labelnhande.setVisible(true);
					btnNewButton.setVisible(true);
					
					
			}else
			{
				try {
					Thread.sleep(5);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}
			
			
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setSize(833, 477);
		shell.setText("client");
		
		 btnKetNoi = new Button(shell, SWT.NONE);
		
		btnKetNoi.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				try {
					
					 socket=new Socket("localhost",7979);
					
					labelchay.setText("running...");
					out=new ObjectOutputStream(socket.getOutputStream());
					
					in=new ObjectInputStream(socket.getInputStream());
					
					tonghopdocghi tonghop=new tonghopdocghi(in, out, CMDqueue, SendQueue,socket);
					tonghop.start();
					btnKetNoi.setVisible(false);
					
					
				} catch (UnknownHostException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}	
			}
		});
		btnKetNoi.setBounds(732, 404, 75, 25);
		btnKetNoi.setText("Run");
		
		labelchay = new Label(shell, SWT.NONE);
		labelchay.setBounds(752, 10, 55, 15);
		
		bntexit = new Button(shell, SWT.NONE);
		bntexit.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Answer anwser=new Answer(" ", " ", " ");
				msg ms2=new msg( new MSGType().getDISCONNECTED(), IP, anwser, "client");
				SendQueue.enqueue(ms2);
				System.exit(0);
				
			}
		});
		bntexit.setBounds(752, 30, 55, 25);
		bntexit.setText("Thoát");
		
		group = new Group(shell, SWT.NONE);
		group.setBounds(89, 10, 657, 97);
		
		lblNewLabel = new Label(group, SWT.NONE);
		lblNewLabel.setBounds(10, 27, 86, 15);
		lblNewLabel.setText("Tên Thí Sinh");
		
		lblNewLabel_1 = new Label(group, SWT.NONE);
		lblNewLabel_1.setBounds(10, 66, 86, 15);
		lblNewLabel_1.setText("ĐẾn từ Lớp");
		
		txttenthisinh = new Text(group, SWT.BORDER);
		txttenthisinh.setBounds(119, 21, 197, 21);
		
		txtdentulop = new Text(group, SWT.BORDER);
		txtdentulop.setBounds(119, 66, 197, 21);
		
		lblNewLabel_2 = new Label(group, SWT.NONE);
		lblNewLabel_2.setBounds(333, 27, 74, 15);
		lblNewLabel_2.setText("số báo danh");
		
		txtsobaodanh = new Text(group, SWT.BORDER);
		txtsobaodanh.setBounds(413, 24, 159, 21);
		
		 btnGui = new Button(group, SWT.NONE);
		btnGui.setBounds(497, 61, 75, 25);
		btnGui.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if((txtdentulop.getText()!="")&&(txtsobaodanh.getText()!=" ")&&(txttenthisinh.getText()!=""))
				{
					
					String str=txttenthisinh.getText()+"|"+txtdentulop.getText()+"|"+txtsobaodanh.getText();
					Answer guitents=new Answer("", "", "");
					 try {
						IP=socket.getInetAddress().getLocalHost().getHostAddress();
					} catch (UnknownHostException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					msg thugui=new msg(new MSGType().getSEND_NAME(), IP, guitents, str);
					SendQueue.enqueue(thugui);
					btnGui.setEnabled(false);
				}
				else
				{
					ms=new MessageBox(shell);
					ms.setMessage("bạn chua ghi đầy đủ thông tin \n vui lòng nhập đầy đủ");
					ms.open();
					
				}
				
			}
		});
		btnGui.setText("Ghi Danh");
		
		group_1 = new Group(shell, SWT.NONE);
		group_1.setBounds(89, 195, 476, 197);
		group_1.setVisible(false);
		 bntA = new Button(group_1, SWT.RADIO);
		 bntA.setBounds(69, 14, 28, 16);
		 bntA.setText("A");
		 
		 labelA = new Label(group_1, SWT.NONE);
		 labelA.setBounds(141, 14, 315, 15);
		 
		  bntB = new Button(group_1, SWT.RADIO);
		  bntB.setBounds(69, 56, 28, 16);
		  bntB.setText("B");
		  
		   labelB = new Label(group_1, SWT.NONE);
		   labelB.setBounds(141, 56, 315, 15);
		   
		    bntC = new Button(group_1, SWT.RADIO);
		    bntC.setBounds(69, 98, 28, 16);
		    bntC.setText("C");
		    
		     labelC = new Label(group_1, SWT.NONE);
		     labelC.setBounds(141, 98, 315, 15);
		     
		      bntD = new Button(group_1, SWT.RADIO);
		      bntD.setBounds(69, 140, 30, 16);
		      bntD.setText("D");
		      
		       labelD = new Label(group_1, SWT.NONE);
		       labelD.setBounds(141, 141, 315, 15);
		        
		        bntnext = new Button(group_1, SWT.NONE);
		        bntnext.setVisible(false);
		        bntnext.addSelectionListener(new SelectionAdapter() {
		        	@Override
		        	public void widgetSelected(SelectionEvent e) {
		        		
		        		
		        		
		        		next=back;
		        		
		        		
		        		if(next<=tongsocautrongde-1)
		        		{ 
		        			
		        			
		        			
		        				
		        				dapan="";
				        		if(bntA.getSelection())
					        		
				        			dapan="A";
				        		else if(bntC.getSelection())
				        			dapan="C";
				        		else if(bntB.getSelection())
				        			dapan="B";
				        		else if(bntD.getSelection())
				        			dapan="D";
				        		else
				        		{
				        			MessageBox dapan1=new MessageBox(shell);
				        			dapan1.setMessage("bạn chưa chọn đáp án vui lòng chọn lại!");
				        			dapan1.open();
				        			
				        			return;
				        			
				        		}
				        		String ID=dethi.get(next).getId();
			        			String macauhoi=dethi.get(next).getMACAUHOI();
			        			String noidung=dethi.get(next).getNOIDUNG();
			        			String malinhvuc=dethi.get(next).getMALINHVUC();
			        			String mucdo=dethi.get(next).getMUCDO();
			        			String A=dethi.get(next).getA();
			        			String B=dethi.get(next).getB();
			        			String C=dethi.get(next).getC();
			        			String D=dethi.get(next).getD();
			        			String dung=dethi.get(next).getDUNG();
			        			String chon=dapan;
			        			traloi trl=new traloi(ID, macauhoi, noidung, malinhvuc, mucdo, A, B, C, D, dung, chon);
		        				
		        			dstl.add( trl);//daluu
		        			bntA.setSelection(false);
		        			bntB.setSelection(false);
		        			bntC.setSelection(false);
		        			bntD.setSelection(false);
		        			back=dstl.Size();
		        			
		        			next+=1;
		        			
		        			if(next<=tongsocautrongde-1)
		        			{
		        				labelnoidungcauhoi.setText(dethi.get(next).getNOIDUNG());
			        			labelA.setText(dethi.get(next).getA());
			        			labelB.setText(dethi.get(next).getB());
			        			labelC.setText(dethi.get(next).getC());
			        			labelD.setText(dethi.get(next).getD());
		        				
		        			}
		        			else
		        			{
		        				labelnoidungcauhoi.setText("");
		        				labelA.setText("");
		        				labelB.setText("");
		        				labelC.setText("");
		        				labelD.setText("");
		        				bntnext.setVisible(false);
		        				
		        			}
		        			
		        			
		        			
		        			
		        		}
		        		else
		        			{
		        			bntnext.setVisible(false);
		        			
		        			}
		        		
		        	}
		        });
		        bntnext.setBounds(391, 172, 75, 25);
		        bntnext.setText("next >>");
		        
		        bnthoangthanh = new Button(group_1, SWT.NONE);
		        bnthoangthanh.setVisible(false);
		        bnthoangthanh.addSelectionListener(new SelectionAdapter() {
		        	@Override
		        	public void widgetSelected(SelectionEvent e) {
		        		MessageBox ms=new MessageBox(shell,SWT.ICON_QUESTION|SWT.YES|SWT.NO);
		        		ms.setMessage("bạn thực sự chắc thực hiện điều này không");
		        		int i=ms.open();
		        		if(i==64)
		        		{
		        			
		        			String iP;
							try {
								Answer tr=new Answer("", "", "");
								iP = socket.getInetAddress().getLocalHost().getHostAddress();
								msg hoanthanh=new msg(new MSGType().getSENT_DATA(), iP, dstl, "client");
								SendQueue.enqueue(hoanthanh);
			        			
							} catch (UnknownHostException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
		        			
		        		
		        		}
		        		
		        	}
		        });
		        bnthoangthanh.setBounds(267, 172, 75, 25);
		        bnthoangthanh.setText("Hoàn thành");
		        
		        group_2 = new Group(shell, SWT.NONE);
		        group_2.setBounds(89, 113, 638, 76);
		        
		         labelnoidungcauhoi = new Label(group_2, SWT.NONE);
		         labelnoidungcauhoi.setBounds(10, 10, 651, 66);
		         labelnoidungcauhoi.setVisible(false);
		         groupketqua = new Group(shell, SWT.NONE);
		         groupketqua.setBounds(571, 195, 185, 197);
		         groupketqua.setText("Kết quả");
		         groupketqua.setVisible(true);
		         
		         Label lblNewLabel_3 = new Label(groupketqua, SWT.NONE);
		         lblNewLabel_3.setBounds(10, 61, 70, 15);
		         lblNewLabel_3.setText("số câu đúng");
		         
		         Label lblNewLabel_4 = new Label(groupketqua, SWT.NONE);
		         lblNewLabel_4.setBounds(10, 136, 55, 15);
		         lblNewLabel_4.setText("tỉ lệ");
		         
		          txtsocaudung = new Label(groupketqua, SWT.NONE);
		         txtsocaudung.setBounds(10, 89, 55, 15);
		         
		          txtdiem = new Label(groupketqua, SWT.NONE);
		         txtdiem.setBounds(10, 172, 55, 15);
		         
		         Label lblNewLabel_7 = new Label(groupketqua, SWT.NONE);
		         lblNewLabel_7.setBounds(94, 89, 55, 15);
		         lblNewLabel_7.setText("câu");
		         
		          labelh = new Label(groupketqua, SWT.CENTER);
		         labelh.setBounds(10, 21, 26, 15);
		         
		          labelph = new Label(groupketqua, SWT.CENTER);
		         labelph.setBounds(60, 21, 26, 15);
		         
		          labels = new Label(groupketqua, SWT.CENTER);
		         labels.setBounds(123, 21, 26, 15);
		         
		         lblH = new Label(groupketqua, SWT.CENTER);
		         lblH.setBounds(37, 21, 17, 15);
		         lblH.setText(":h");
		         
		         lblNewLabel_5 = new Label(groupketqua, SWT.CENTER);
		         lblNewLabel_5.setBounds(94, 21, 23, 15);
		         lblNewLabel_5.setText(":ph");
		         
		         lblS = new Label(groupketqua, SWT.CENTER);
		         lblS.setBounds(156, 21, 19, 15);
		         lblS.setText(":s");
		         
		         btnNewButton = new Button(shell, SWT.NONE);
		         btnNewButton.setVisible(false);
		         btnNewButton.addSelectionListener(new SelectionAdapter() {
		         	@Override
		         	public void widgetSelected(SelectionEvent e) {
		         		batdauthi=1;
		         		bntnext.setVisible(true);
		         		
		         		bnthoangthanh.setVisible(true);
		         		
		         		group_1.setVisible(true);
		         		labelnoidungcauhoi.setVisible(true);
		         		btnNewButton.setEnabled(false);
		         	}
		         });
		         btnNewButton.setBounds(649, 404, 75, 25);
		         btnNewButton.setText("bắt đầu thi");
		         
		         labelnhande = new Label(shell, SWT.NONE);
		         labelnhande.setBackground(SWTResourceManager.getColor(SWT.COLOR_CYAN));
		         labelnhande.setBounds(430, 404, 135, 15);
		         labelnhande.setText("trình trạng đã nhận đề");
		         labelnhande.setVisible(false);
		       //  labelnhande.setBackground(color)
		         

	}
	public void clock(int thoigian)
	{
		interval=thoigian;
		 timer=new Timer();
		 timer.scheduleAtFixedRate(new TimerTask() {

		        public void run() {
		           
		            if (interval == 1)
		            
		                timer.cancel();
		            
		              --interval;
		              dong=interval;
		           
		             // System.out.println(interval);
		        }
		    }, 1000, 1000);
		
		
		
	}
}
